import { ref } from 'vue'

interface User {
  id: number
  username: string
  avatar: string
  bio: string
  followers: number
  following: number
  posts: number
}

export const useAuth = () => {
  const user = ref<User | null>(null)
  const isAuthenticated = ref(false)

  const login = async (username: string, password: string) => {
    try {
      // TODO: 调用后端登录API
      const response = await fetch('/api/auth/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ username, password })
      })
      
      if (response.ok) {
        const data = await response.json()
        user.value = data.user
        isAuthenticated.value = true
        return true
      }
      return false
    } catch (error) {
      console.error('登录失败:', error)
      return false
    }
  }

  const register = async (username: string, password: string, email: string) => {
    try {
      // TODO: 调用后端注册API
      const response = await fetch('/api/auth/register', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ username, password, email })
      })
      
      if (response.ok) {
        const data = await response.json()
        user.value = data.user
        isAuthenticated.value = true
        return true
      }
      return false
    } catch (error) {
      console.error('注册失败:', error)
      return false
    }
  }

  const logout = () => {
    user.value = null
    isAuthenticated.value = false
  }

  const checkAuth = async () => {
    try {
      // TODO: 调用后端验证API
      const response = await fetch('/api/auth/check')
      if (response.ok) {
        const data = await response.json()
        user.value = data.user
        isAuthenticated.value = true
        return true
      }
      return false
    } catch (error) {
      console.error('验证失败:', error)
      return false
    }
  }

  return {
    user,
    isAuthenticated,
    login,
    register,
    logout,
    checkAuth
  }
} 